package internal

import (
	"dlist/common/datetime"
	"dlist/global"
	"dlist/settings"
	"strconv"
	"time"
)

type Manager struct {
}

func (m *Manager) Create(issue *Issue) {
	// Create
	global.DB.Create(issue)
}

func (m *Manager) Delete(id uint) {
	issue := &Issue{
		ID: id,
	}
	global.DB.Delete(issue)
}

func (m *Manager) Finish(id uint) {
	issue := &Issue{
		ID:        id,
		UpdatedAt: datetime.Now(),
		Status:    1,
	}
	global.DB.Select("Status").Save(issue)
}

func (m *Manager) UndoFinish(id uint) {
	issue := &Issue{
		ID:        id,
		UpdatedAt: datetime.Now(),
		Status:    0,
	}
	global.DB.Select("Status").Save(issue)
}

func (m *Manager) Update(issue *Issue) {
	global.DB.Save(issue)
}

func (m *Manager) List() []Issue {
	issues := make([]Issue, 0)
	recentDays, _ := strconv.Atoi(settings.Get(settings.RecentDays))
	showFinished, _ := strconv.ParseBool(settings.Get(settings.ShowFinished))
	now := time.Now()
	tx := global.DB.Where("updated_at>?", datetime.Of(now.Add(time.Duration(recentDays)*-24*time.Hour)))
	if !showFinished {
		tx.Where("status=0")
	}
	tx.Find(&issues)
	return issues
}

func (m *Manager) GetByID(id uint) Issue {
	var issue Issue
	global.DB.Where("id=?", id).First(&issue)
	return issue
}
